package ca.paulshin.yunatube.main;

import static ca.paulshin.yunatube.database.YuNaTubeSqliteDatabase.getInstance;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.CursorAdapter;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ListView;
import android.widget.TextView;
import ca.paulshin.yunatube.R;
import ca.paulshin.yunatube.YunaTubeBaseFragment;
import ca.paulshin.yunatube.database.Schema.YouTubeColumns;
import ca.paulshin.yunatube.youtube.YouTubeActivity;

public class SearchFragment extends YunaTubeBaseFragment {
	private EditText searchBox;
	private Button clear;
	private ListView listView;
	private CursorAdapter adapter;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}
	
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.search, null);
		
		searchBox = (EditText) view.findViewById(R.id.search);
		clear = (Button) view.findViewById(R.id.search_clear);
		listView = (ListView) view.findViewById(R.id.search_results);
		
		searchBox.setFocusableInTouchMode(true);
		searchBox.setFocusable(true);
		searchBox.requestFocus();
		
		// Show keyboard
		InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.showSoftInput(searchBox, InputMethodManager.SHOW_FORCED);
		
		clear.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				searchBox.setText("");
				clear.setVisibility(View.INVISIBLE);
			}
		});

		searchBox.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
				int length = searchBox.getText().toString().length();
				if (length == 0) {
					clear.setVisibility(View.INVISIBLE);
					listView.setVisibility(View.INVISIBLE);
				}
				else if (length > 1) {
					clear.setVisibility(View.VISIBLE);
					listView.setVisibility(View.VISIBLE);
					if (adapter != null) {
						adapter.getFilter().filter(cs);
					}
				}
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
			}

			@Override
			public void afterTextChanged(Editable arg0) {
			}
		});
		
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> l, View view, int position, long id) {
				String[] set = (String[])view.getTag();
				Bundle bundle = new Bundle();
				bundle.putStringArray(YouTubeActivity.EXTRA_YOUTUBE_CLIPSET, new String[] { null, set[0], set[1] });
				Intent intent = new Intent(getActivity(), YouTubeActivity.class);
				intent.putExtras(bundle);
				startActivity(intent);
				getActivity().overridePendingTransition(R.anim.open_next, R.anim.close_main);
			}
		});

		listView.setFastScrollEnabled(true);
		
		adapter = new CustomCursorAdapter(getActivity(), null);
		adapter.setFilterQueryProvider(new FilterQueryProvider() {
			@Override
			public Cursor runQuery(CharSequence constraint) {
				if (TextUtils.isEmpty(constraint)) return null;
				
				Cursor cursor = getInstance().fetchFilteredClips(constraint.toString());
				return cursor;
			}
		});

		listView.setAdapter(adapter);
		
		return view;
	}
	
	@Override
	public void onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu, com.actionbarsherlock.view.MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);
		menu.removeItem(R.id.search);
	}
	
	/*
	 * Adapter
	 */
	private class CustomCursorAdapter extends CursorAdapter {

		public CustomCursorAdapter(Context context, Cursor c) {
			super(context, c, 0);
		}

		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			TextView titleView = (TextView) view.findViewById(R.id.title);
			String title = cursor.getString(cursor.getColumnIndex(YouTubeColumns.title));
			String url = cursor.getString(cursor.getColumnIndex(YouTubeColumns.url));
			titleView.setText(title);
			view.setTag(new String[] { title, url });
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			LayoutInflater inflater = LayoutInflater.from(context);
			View v = inflater.inflate(R.layout.search_row, parent, false);
			bindView(v, context, cursor);
			return v;
		}
	}
	
	@Override
	public int getTitle() {
		return R.string.actionbar_search;
	}

	@Override
	protected boolean getNetworkCheck() {
		return false;
	}

	@Override
	protected String getTrackerId() {
		return "search";
	}
}